package 多线程.三个线程实现顺序打印;

/**
 * 用volatile修饰变量, volatile能保证变量的更改对所有线程可见。
 */
public class Test3 {
    //判断是否执行：1表示应该A执行，2表示应该B执行，3表示应该C执行
    private static volatile int state = 1;
    public static void main(String[] args) {
        Test3 t = new Test3();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                t.printA();
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }
    public static void printA(){
        while (state != 1){

        }
        System.out.println("A");
        state++;
    }

    public static void printB()  throws InterruptedException{
        while (state != 2){

        }
        System.out.println("B");
        state++;
    }
    public static void printC() throws InterruptedException{
        while (state != 3){

        }
        System.out.println("C");
        state++;
    }
}
